package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "地址簿接口")
@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressController {
    @Autowired
    private AddressService addressService;

    // 新增地址
    @PostMapping
    @ApiOperation("新增地址")
    public Result<String> addAddress(@RequestBody AddressBook addressInfo) {
        addressService.addAddress(addressInfo);

        return Result.success();
    }

    // 查询登录用户的地址
    @GetMapping("/list")
    @ApiOperation("查询登陆用户所有地址")
    public Result<List<AddressBook>> getUserAddress() {
        AddressBook addressInfo = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
        List<AddressBook> addressBookList = addressService.getUserAddressList(addressInfo);

        return Result.success(addressBookList);
    }

    // 查询登录用户的默认地址
    @GetMapping("/default")
    @ApiOperation("查询登陆用户默认地址")
    public Result<AddressBook> getUserAddressDefault() {
        AddressBook addressInfo = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(StatusConstant.ENABLE)
                .build();
        List<AddressBook> addressBookList = addressService.getUserAddressList(addressInfo);

        return Result.success(addressBookList.get(0));
    }

    // 根据id获取当前用户的地址信息
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址信息")
    public Result<AddressBook> getAddressById(@PathVariable Long id) {
        AddressBook addressInfo = addressService.selectById(id);

        return Result.success(addressInfo);
    }

    // 修改地址信息
    @PutMapping
    @ApiOperation("修改地址信息")
    public Result<String> updateAddressInfo(@RequestBody AddressBook addressInfo) {
        addressInfo.setUserId(BaseContext.getCurrentId());
        addressService.updateAddressInfo(addressInfo);


        return Result.success();
    }

    // 更改默认地址
    @PutMapping("/default")
    @ApiOperation("修改默认地址")
    public Result<String> updateDefaultAddress(@RequestBody AddressBook addressInfo) {
        addressInfo.setUserId(BaseContext.getCurrentId());
        addressService.updateDefaultAddress(addressInfo);

        return Result.success();
    }

    // 删除地址
    @DeleteMapping
    @ApiOperation("删除地址")
    public Result<String> deleteAddress(@RequestParam Long id) {
        addressService.deleteAddress(id);

        return Result.success();
    }
}
